package handlers

import (
	"net/http"
	"ota-backend/config"
	"ota-backend/models"

	"github.com/gin-gonic/gin"
)

// ProductHandler 产品处理器
type ProductHandler struct{}

// NewProductHandler 创建产品处理器
func NewProductHandler() *ProductHandler {
	return &ProductHandler{}
}

// CreateProduct 创建产品
func (h *ProductHandler) CreateProduct(c *gin.Context) {
	var product models.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查产品名称是否已存在
	var existingProduct models.Product
	if err := config.DB.Where("name = ?", product.Name).First(&existingProduct).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "产品名称已存在"})
		return
	}

	// 检查公共产品ID是否已存在
	if err := config.DB.Where("public_id = ?", product.PublicID).First(&existingProduct).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "公共产品ID已存在"})
		return
	}

	if err := config.DB.Create(&product).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, product)
}

// GetProducts 获取产品列表
func (h *ProductHandler) GetProducts(c *gin.Context) {
	var products []models.Product

	if err := config.DB.Find(&products).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, products)
}

// GetProduct 获取单个产品
func (h *ProductHandler) GetProduct(c *gin.Context) {
	id := c.Param("id")

	var product models.Product
	if err := config.DB.First(&product, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// UpdateProduct 更新产品
func (h *ProductHandler) UpdateProduct(c *gin.Context) {
	id := c.Param("id")

	var product models.Product
	if err := config.DB.First(&product, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	var updateData models.Product
	if err := c.ShouldBindJSON(&updateData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查名称是否与其他产品冲突
	if updateData.Name != "" && updateData.Name != product.Name {
		var existingProduct models.Product
		if err := config.DB.Where("name = ? AND id != ?", updateData.Name, id).First(&existingProduct).Error; err == nil {
			c.JSON(http.StatusConflict, gin.H{"error": "产品名称已存在"})
			return
		}
	}

	// 检查公共产品ID是否与其他产品冲突
	if updateData.PublicID != "" && updateData.PublicID != product.PublicID {
		var existingProduct models.Product
		if err := config.DB.Where("public_id = ? AND id != ?", updateData.PublicID, id).First(&existingProduct).Error; err == nil {
			c.JSON(http.StatusConflict, gin.H{"error": "公共产品ID已存在"})
			return
		}
	}

	if err := config.DB.Model(&product).Updates(updateData).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, product)
}

// DeleteProduct 删除产品
func (h *ProductHandler) DeleteProduct(c *gin.Context) {
	id := c.Param("id")

	var product models.Product
	if err := config.DB.First(&product, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	// 检查是否有关联的固件
	var firmwareCount int64
	config.DB.Model(&models.Firmware{}).Where("product_id = ?", id).Count(&firmwareCount)
	if firmwareCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "产品下存在固件，无法删除"})
		return
	}

	// 检查是否有关联的任务
	var taskCount int64
	config.DB.Model(&models.Task{}).Where("product_id = ?", id).Count(&taskCount)
	if taskCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "产品下存在任务，无法删除"})
		return
	}

	if err := config.DB.Delete(&product).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "产品删除成功"})
}
